/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import entity.Iphone;
import entity.Iphonetype;
import java.util.ArrayList;
import org.hibernate.Query;
import org.hibernate.Session;
import util.AppHibernateUtil;

/**
 *
 * @author Programer
 */
public class IphoneDAO {
    /////////////////////////////////////////////////////////////////
    ////Init Sigleton pattern
    private static IphoneDAO Instance;
    private IphoneDAO() {
    }
    public static IphoneDAO getInstance() {
        if(Instance == null) {
            Instance = new IphoneDAO();
        }
        return Instance;
    }
    
    public static ArrayList<Iphone> getProductsByType(Iphonetype type) {
        ArrayList<Iphone> list = new ArrayList<Iphone>();
        
        Session session = AppHibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        
        String hql = "from Iphone where productType=:type";
        
        Query query = session.createQuery(hql);
        query.setParameter("type", type.getId());
        
        list = (ArrayList)query.list();
        
        return list;
    }
    
    public static Iphone getProductByID(String id) {
        Iphone type = new Iphone();

        Session session = AppHibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();

        String hql = "from Iphone where productid=:_id";

        Query query = session.createQuery(hql);
        query.setParameter("_id", id);

        ArrayList<Iphone> list = (ArrayList<Iphone>) query.list();

        if (list.size() > 0) {
            type = (Iphone) query.list().get(0);
        }

        return type;
    }
    
    public static ArrayList<Iphone> getProductList() {
        ArrayList<Iphone> type = new ArrayList<Iphone>();

        Session session = AppHibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();

        String hql = "from Iphone";

        Query query = session.createQuery(hql);

        type = (ArrayList<Iphone>) query.list();

        return type;
    }
    
    public boolean insertIphone( Iphone ip) {
        boolean success = false;
        Session session = AppHibernateUtil.getSessionFactory().openSession();
        try {
            session.beginTransaction();
            session.save(ip);
            session.getTransaction().commit();
            success = true;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return success;
        } finally {
            session.close();
        }
        return success;
    }
}
